//
//  OrderTableViewController.swift
//  ShopIOS
//
//  Created by Apple on 2019/7/26.
//  Copyright © 2019 Apple. All rights reserved.
//

import UIKit

class OrderTableViewController: UITableViewController,EmptyViewProtocol {
    var showEmtpy: Bool{
        get {
            return orders.count == 0
        }
    }
    var label:UILabel?
    
    var orderStatus:Int!
    var pageNo:Int=1
    var dataSouce:mOrder!
    var orders=[mOrders]()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        
        tableView.register(UINib(nibName: "OrderTableViewCell", bundle: nil), forCellReuseIdentifier: "reuseIdentifier")
        tableView.register(UINib(nibName: "OrderHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "header")
        tableView.register(UINib(nibName: "OrderFooterView", bundle: nil), forHeaderFooterViewReuseIdentifier: "footer")
        tableView.separatorStyle = .none
        tableView.contentInset=UIEdgeInsets(top: 10, left: 0, bottom: 10, right: 0)
        tableView.setEmtpyViewDelegate(target: self)
        //refresh
        let header = TTRefreshHeader.init(refreshingBlock: {[weak self] in
            guard let strongSelf = self else{return}
            strongSelf.pageNo = 1
            strongSelf.tableView.mj_footer.state = .idle
            strongSelf.tableView.mj_header.endRefreshing()
            strongSelf.loadData()
        })
        
        tableView.mj_header = header;
        
        let footer = TTRefreshFooter  {  [weak self] in
            guard let strongSelf = self else{return}
            strongSelf.pageNo = strongSelf.pageNo + 1
            strongSelf.loadData();
        }
        
        tableView.mj_footer = footer
        tableView.mj_footer.isHidden = false
    }
    init(status:Int){
        super.init(style: UITableView.Style.grouped)
        self.orderStatus=status
        loadData()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func loadData(){
        var d = ["userkey":userkey,
                 "orderStatus":"\(orderStatus!)",
                 "pageNo":String(pageNo),
                 "pageSize":"20",
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as! [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.get(url: GetOrders, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            
            
            if ss.pageNo == 1{ ss.orders.removeAll()}
            
            if ss.tableView.mj_header.isRefreshing(){
                ss.tableView.mj_header.endRefreshing()
            }else if ss.tableView.mj_footer.isRefreshing() {
                ss.tableView.mj_footer.endRefreshing()
                
            }
            ss.dataSouce = mOrder.init(json: res)
            
            if ss.dataSouce.Orders.count>0 {
                if ss.tableView.mj_footer.isHidden && ss.dataSouce.Orders.count > 0 {
                    ss.tableView.mj_footer.isHidden = false
                }
                ss.orders.insert(contentsOf: ss.dataSouce.Orders, at: ss.orders.count)
                if ss.orders.count < 20 {
                    ss.tableView.mj_footer.state = .noMoreData
                }
            }else {
                ss.tableView.mj_footer.state = .noMoreData
            }
            
            ss.tableView.reloadData()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
            if ss.tableView.mj_header.isRefreshing(){ss.tableView.mj_header.endRefreshing()}
            else if ss.tableView.mj_footer.isRefreshing() {ss.tableView.mj_footer.endRefreshing()}
        }
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return orders.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return orders[section].itemInfo.count
    }

    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! OrderTableViewCell
        let item=orders[indexPath.section].itemInfo[indexPath.row]
        if (item.image != nil){
           cell.iv_icon.setImage(path: URL.init(string: item.image!)!)
        }
        cell.lb_name.text=item.productName
        cell.lb_price.text="￥\(item.price)"
        cell.lb_count.text="x\(item.count)"
        cell.selectionStyle = .none
        return cell
    }

    /*分区头部部高度*/
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 55
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let sectionHeadView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") as! OrderHeaderView
        let item=orders[section]
        sectionHeadView.lb_shopname.text=item.shopname!
        sectionHeadView.lb_status.text=item.status!
        
        return sectionHeadView
        
    }
    /*分区尾部高度*/
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 111
    }
    override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let sectionFootView=tableView.dequeueReusableHeaderFooterView(withIdentifier: "footer") as! OrderFooterView
        let item=orders[section]
        sectionFootView.lb_total.text="共\(item.productCount)件商品 合计：￥\(item.orderTotalAmount!)"
        sectionFootView.uv_footer.corner(byRoundingCorners: [.bottomLeft,.bottomRight], radii: 10)
        sectionFootView.btn_pay.border(color: UIColor.red, width: 1, type: UIBorderSideType.UIBorderSideTypeAll, cornerRadius: 15)
        sectionFootView.btn_pay.setTitleColor(UIColor.red, for: UIControl.State.normal)
        sectionFootView.btn_pay.contentEdgeInsets=UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        sectionFootView.btn_pay.snp.makeConstraints{(mask) in
            mask.height.equalTo(30)
        }
        sectionFootView.btn_pay.tag=section
        sectionFootView.btn_pay.addTarget(self, action: #selector(showPop(sender:)), for: UIControl.Event.touchUpInside)
        
        sectionFootView.btn_cancel.border(color: UIColor.lightGray, width: 1, type: UIBorderSideType.UIBorderSideTypeAll, cornerRadius: 15)
        sectionFootView.btn_cancel.setTitleColor(UIColor.black, for: UIControl.State.normal)
        sectionFootView.btn_cancel.contentEdgeInsets=UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
        sectionFootView.btn_cancel.snp.makeConstraints{(mask) in
            mask.height.equalTo(30)
        }
        return sectionFootView
    }
    override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.corner(byRoundingCorners: [.topLeft,.topRight], radii: 10)
    }
    override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
//        view.corner(byRoundingCorners: [.bottomLeft,.bottomRight], radii: 10)
    }
    
    func configEmptyView() -> UIView? {
        let view=Bundle.main.loadNibNamed("NoOrderView", owner: nil, options: nil)?[0]as?UIView
        view?.height=screenH-90-kStatusBarHeight
        view?.width=screenW
        return view
    }
    @objc func showPop(sender:UIButton){
        print(sender.tag)
        let item=orders[sender.tag]
        let popview = ZXPopView.init(frame: CGRect(x: 0, y: 0, width: screenW, height: screenH))
        let payview=Bundle.main.loadNibNamed("PayWayView", owner: nil, options: nil)?[0]as!PayWayView
        payview.uv_wallet.layer.cornerRadius=10
        payview.uv_wallet.layer.maskedCorners=CACornerMask(rawValue: CACornerMask.layerMinXMinYCorner.rawValue|CACornerMask.layerMaxXMinYCorner.rawValue)
        payview.uv_wechat.layer.cornerRadius=10
        payview.uv_wechat.layer.maskedCorners=CACornerMask(rawValue: CACornerMask.layerMinXMaxYCorner.rawValue|CACornerMask.layerMaxXMaxYCorner.rawValue)
        payview.uv_cancel.layer.cornerRadius=10
        
        let ges_wallet=UITapGestureRecognizer(target: self, action: #selector(wallet(sender:)))
        payview.uv_wallet.addGestureRecognizer(ges_wallet)
        ges_wallet.view!.tag=sender.tag
        
        let ges_alipay=UITapGestureRecognizer(target: self, action: #selector(alipay(sender:)))
        payview.uv_alipay.addGestureRecognizer(ges_alipay)
        ges_alipay.view!.tag=sender.tag
        
        let ges_wechat=UITapGestureRecognizer(target: self, action: #selector(wechat(sender:)))
        payview.uv_wechat.addGestureRecognizer(ges_wechat)
        ges_wechat.view!.tag=sender.tag
        
        popview.contenView = payview
        popview.anim = 1
        payview.snp.makeConstraints { (make) in
            make.width.equalTo(screenW)
            make.height.equalTo(230)
            make.bottom.equalTo(0)
        }
        popview.showInWindow()
    }
    @objc func wallet(sender:UITapGestureRecognizer){
        print(sender.view!.tag)
    }
    @objc func alipay(sender:UITapGestureRecognizer){
        print(sender.view!.tag)
    }
    @objc func wechat(sender:UITapGestureRecognizer){
        print(sender.view!.tag)
    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
